#include "tcp_client.h"

#include <stdio.h>

#include "ohos_init.h"
#include "cmsis_os2.h"

#include "oled.h"

server_data_t server_data;

int connect_to_tcp_server(const char* host_ip, unsigned short port)
{
    uint8_t connecting_server[] = {"Connecting server..."};
    uint8_t connect_failed[] = {"Connect tcp failed."};

    server_data.server_connect_state = 0;
    server_data.last_server_connect_state = 0;
    //ssize_t retval = 0;
    //printf("HarmonyOS will connect to %s:%d\r\n", host_ip, port);
    OLED_Clear_Line(1);
    OLED_Show_String(0, 1, 8, connecting_server);
    server_data.sockfd = socket(AF_INET, SOCK_STREAM, 0); // TCP socket

    struct sockaddr_in serverAddr = {0};
    serverAddr.sin_family = AF_INET;  // AF_INET表示IPv4协议
    serverAddr.sin_port = htons(port);  // 端口号，从主机字节序转为网络字节序
    if (inet_pton(AF_INET, host_ip, &serverAddr.sin_addr) <= 0)
    {  // 将主机IP地址从“点分十进制”字符串 转化为 标准格式（32位整数）
        printf("inet_pton failed!\r\n");
        clear(server_data.sockfd);
        return -1;
    }

    // 尝试和目标主机建立连接，连接成功会返回0 ，失败返回 -1
    if (connect(server_data.sockfd, (struct sockaddr *)&serverAddr, sizeof(serverAddr)) < 0)
    {
        printf("connect failed!\r\n");
        oled_clear_line(0, 0, 10, 17);
        OLED_Clear_Line(1);
        OLED_Show_String(0, 1, 8, connect_failed);
        clear(server_data.sockfd);
        return -1;
    }
    //printf("connect to server %s success!\r\n", host_ip);
    server_data.server_connect_state = 1;
    send(server_data.sockfd, "dl", 3, 0);    //登录服务器
    
    return 0;
}

void clear(int sockfd)
{
    printf("do_cleanup...\r\n");
    lwip_close(sockfd);
    server_data.server_connect_state = 0;
}